<?php

defined('BASEPATH') or die('forbidden');

class Area_Controller Extends Controller {
	#public $act_cfg;
    private $wholeServerHost;
    public $statelist = array();

    function _init() {
    	include  'ActivityCfg.php';
    	#var_dump(translate('ACTIVITY_TOPFIGHT_MATCH1') . 1 . translate('ACTIVITY_TOPFIGHT_MATCH2'));
        check_level(50, segment(0), segment(1), segment(2, 'index'));
        $this->statelist = array(
            '2' => translate('AREA_STATUS_OK'),
            '7' => translate('AREA_STATUS_HOT'),
            '1' => translate('AREA_STATUS_REPAIR'),
            '8' => translate('AREA_STATUS_WAIT'),
        );
        
        $this->flaglist = array( '0' => translate('AREA_FLAG_NEW') , '1' => translate('AREA_FLAG_SUGGEST'),'2'=>  translate('AREA_FLAG_NULL'));
        $this->view->assign("statelist", $this->statelist);
        $this->view->assign("flaglist", $this->flaglist);
        $config = get_config();
        $this->wholeServerHost = $config['host_url'];
    }

    function index() {
        //$data='{"SessionID":"","SessionKey":""}';
        //$rows = vpost('http://119.23.148.240:8081/gm_server_list',10,$data);
        //var_dump(json_decode($rows,true));
        $this->view->display("area/area/index");
    }

    function flexigrid() {
        list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();
        $data=array();
        $post_data='{"SessionID":"ewewqw","SessionKey":"wqqew"}';
        $row = vpost($this->wholeServerHost.'gm_server_list',3,$post_data);
        $rows=json_decode($row,true);
        $total=count($rows['SvrList']);
        foreach ($rows['SvrList'] as $k=>$v){
            $v['SvrOpenTime'] = get_datetime($v['SvrOpenTime']);
            $data[$k]=array('id' => $v['SvrID'], 'cell' => $v);
        }
//        $sql = "SELECT COUNT(*) AS num FROM {pre}areasample WHERE {$where}";
//        $one = $this->db->one($sql);
//        $total = $one['num'];
//        $orderby = $sortname ? "ORDER BY {$sortname} {$sortorder} " : "";
//        $this->db->query("SELECT {$colsinfo} FROM {pre}areasample WHERE {$where} {$orderby} LIMIT {$offset},{$rp}");
//        while ($n = $this->db->get_array('default')) {
//            $n['opentime'] = get_datetime($n['opentime']);
//            //$n[10] = str_replace("/api/", "", $n[3]) . site_url();
//            $n['lastopentime'] = get_datetime($n['lastopentime']);
//            $rows[] = array('id' => $n['id'], 'cell' => $n);
//        }
        $result = array(
            'page' => $page,
            'total' => $total,
            'rows' => $data
        );
        echo json_encode($result);
    }

    function add($id = 0) {

        if (is_submit()) {
            $rowdata = $_POST['row'];
            //$rowdata['version'] = addslashes(json_encode(explode("/r/n", $rowdata['version'])));
            $rowdata['host'] = get_full_url($rowdata['host']);
            $rowdata['opentime'] = $rowdata['opentime'] ? strtotime($rowdata['opentime']) : 0;
            $one = $this->db->one("SELECT * FROM {pre}areasample WHERE id='{$rowdata['id']}'");
            if (is_array($one))
                error(translate('C_EXISTED_PARAM_ID', $rowdata['id']));
            //$rowdata['father_id'] = $rowdata['father_id'] ? $rowdata['father_id'] : $rowdata['id'];
            
            include_once CONFIGPATH."config.php";
            
            $rowdata['id']=(int)$rowdata['id'];
            $rowdata['opentime']=  (int)$rowdata['opentime'];
            $rowdata['state']=(int)$rowdata['state'];
            $rowdata['flag']=(int)$rowdata['flag'];
            $rows[] = $rowdata;
            $list['arealist'] = $rows;
            $jsonStr = json_encode($list);
            $result = vpost($this->wholeServerHost."areas=$jsonStr&action=47");
            if($result){
                $id = $this->db->insert("{pre}areasample", $rowdata);
                $this->db->query("UPDATE {pre}areasample SET weigh=id WHERE id='{$id}'");
                //$rowdata['host_url'] = dirname(base_url(1)) . '/api/';
                //set_async_area($rowdata['id'], 'area/area/edit', $rowdata);
                insert_log(translate('MENU_AREA_AREA'),translate('ADD'), null,$id);
                cp_tips("success", $id);
            }else{
                cp_tips("error", $id);
            }

        }
        $lastarea = $this->db->one("SELECT * FROM {pre}areasample ORDER BY weigh DESC");
        if ($lastarea) {
            $lastarea['idarr'] = explode(":", $lastarea['id']);
            $lastarea['hostarr'] = explode(":", $lastarea['host']);
        }
        $this->view->assign("lastarea", $lastarea);
        //$this->view->assign("fatherlist", $this->form->select("row[father_id]", array_merge(array(translate('AREA_SELF')), get_area_list_option()), '', array('id' => 'father_id')));
        $this->view->display("area/area/add");
    }

    function edit($id = 0) {
        if ($id === 0)
            error(translate('C_INVALID_PARAM_ID', $id));
        $data=array();
        $post_data='{"SessionID":"","SessionKey":""}';
        $row = vpost($this->wholeServerHost.'gm_server_list',3,$post_data);
        $rows=json_decode($row,true);
        foreach ($rows['SvrList'] as $k=>$v){
            //$v['SvrOpenTime'] = get_datetime($v['SvrOpenTime']);
            //$data[$k]=array('SvrID' => $v['SvrID'], 'cell' => $v);
            if($v['SvrID'] == $id){
                $data=$v;
                var_dump($data);
            }
        }
        //$row = $this->db->one("SELECT * FROM {pre}areasample WHERE id=1");
        //var_dump($data);
        if (!is_array($data))
            error(translate('C_INVALID_PARAM_ID', $id));

        if (is_submit()) {
			#var_dump($_POST);
			
            
            #var_dump($row['opentime']);
            #var_dump($tmp_param1);
            $rowdata = $_POST['row'];
            #var_dump($_POST['row']);
            //$rowdata['version'] = addslashes(json_encode(explode("/r/n", $rowdata['version'])));
            $rowdata['SvrOpenTime'] = $rowdata['SvrOpenTime'] ? strtotime($rowdata['SvrOpenTime']) : 0;
            //$tmp_param1 = (int)$rowdata['SvrOpenTime'];
            #var_dump($tmp_param1);
            #exit(0);
//            $one='';
//            $post_data='{"SessionID":"","SessionKey":""}';
//            $row = vpost($this->wholeServerHost.'gm_server_list',3,$post_data);
//            $rows=json_decode($row,true);
//            foreach ($rows['SvrList'] as $k=>$v){
//                $v['SvrOpenTime'] = get_datetime($v['SvrOpenTime']);
//                if($rowdata['SvrID']==$v['SvrID']){
//                    return $one=$v;
//                }
//            }
            //$one = $this->db->one("SELECT * FROM {pre}areasample WHERE id='{$rowdata['id']}'");
//            if (!is_array($one))
//                error(translate('C_EXISTED_PARAM_ID', $rowdata['SvrID']));

            $rowdata['SvrID']=(int)$rowdata['SvrID'];
            $rowdata['SvrOpenTime']=  (int)$rowdata['SvrOpenTime'];
            $rowdata['State']=(int)$rowdata['SvrState'];
            //$rowdata['flag']=(int)$rowdata['flag'];
            $jsonStr = json_encode($rowdata);
            var_dump($jsonStr);

            $result = vpost($this->wholeServerHost.'gm_set_server_state',3,$jsonStr);

//            if($tmp_param1 != $row['SvrOpenTime'])
//            {
//                $act_cfg = new ActivityCfg();
//            	#var_dump("updateStartTime is called!");
//				#exit(0);
//                $act_cfg->updateStartTime($rowdata['SvrID'], $tmp_param1);
//
//            }
#                        exit(0);
#			var_dump($this->wholeServerHost."areas=$jsonStr&action=47");
			#exit(0);
            $code=json_decode($result,true);
            if($code['RetCode']==0){
                //$this->db->update("{pre}areasample", $rowdata, array('id' => $id));
                insert_log(translate('MENU_AREA_AREA'),translate('EDIT'), $row, $rowdata);
                cp_tips("success", $id);
            }else{
                cp_tips("error", $id);
            }


        }
        //$father_id = $row['id'] == $row['father_id'] ? '' : $row['father_id'];
        //$this->view->assign("fatherlist", $this->form->select("row[father_id]", array_merge(array(translate('AREA_SELF')), get_area_list_option()), $father_id, array('id' => 'father_id')));
        //$row['version'] = get_json_array($row['version']);
        $this->view->display("area/area/edit", array('row' => $data));
    }

    function maintain($id = 0){
        if ($id === 0)
            error(translate('C_INVALID_PARAM_ID', $id));
        $data=array();
        $post_data='{"SessionID":"","SessionKey":""}';
        $row = vpost($this->wholeServerHost.'gm_server_list',3,$post_data);
        $rows=json_decode($row,true);
        foreach ($rows['SvrList'] as $k=>$v){
            if($v['SvrID'] == $id){
                $data=$v;
            }
        }
        //var_dump($data);
        if (!is_array($data))
            error(translate('C_INVALID_PARAM_ID', $id));

        if (is_submit()) {
            $rowdata = $_POST['row'];
            var_dump($_POST['row']);
            //$rowdata['version'] = addslashes(json_encode(explode("/r/n", $rowdata['version'])));
            $maintain_data['SessionID'] = "ewewqw";
            $maintain_data['SessionKey'] = "wqqew";
            $maintain_data['SvrID'] = (int)$rowdata['SvrID'];
            $maintain_data['SvrName'] = $rowdata['SvrName'];
            $maintain_data['SvrStatus'] = (int)$rowdata['SvrState'];
            $maintain_data['SvrNotice'] = $rowdata['SvrNotice'];
            $jsonStr = json_encode($maintain_data);
            //var_dump($maintain_data);

            $result = vpost($rowdata['SvrOutAddr'] . '/set_server_info', 3, $jsonStr);
            $code = json_decode($result, true);
            if ($code['RetCode'] == 0) {
                //$this->db->update("{pre}areasample", $rowdata, array('id' => $id));
                insert_log(translate('MENU_AREA_AREA'), translate('MAINTAIN'), $row, $rowdata);
                cp_tips("success", $id);
            } else {
                cp_tips("error", $id);
            }
        }
        $this->view->display("area/area/maintain", array('row' => $data));
    }

    function del($id = 0) {
        $c = 0;
        $r = '';
        if ($id === 0)
            json_output($c, translate('C_INVALID_PARAM_ID', $id));
        $row = $this->db->one("SELECT * FROM {pre}areasample WHERE id='{$id}'");
        if (!is_array($row))
            json_output($c, translate('C_INVALID_PARAM_ID', $id));
        if ($this->db->delete('{pre}areasample', array('id' => $id))) {
            insert_log(translate('MENU_AREA_AREA'),translate('DEL'), array('id'=> $id));
            $c = 1;
        } else {
            $r = translate('C_TIPS_ERROR_TEXT');
        }
        json_output($c, $r);
    }

    function multi() {
        $type = $this->input->post("type");
        $ids = $this->input->post("ids");
        $c = 0;
        $r = '';
        $allids = $ids = explode(',', $ids);
        if (count($ids) == 0) {
            $r = translate('C_INVALID_PARAMS');
        } else {
            $ids = "'" . implode("','", $ids) . "'";
            if ($type == 'delete') {
                $this->db->query("DELETE FROM {pre}areasample WHERE id IN ({$ids})");
                insert_log(translate('MENU_AREA_AREA'),translate('MULTI_DEL'), array('ids'=> implode(",", $allids)));
                $c = 1;
            } else if ($type == 'accept') {
                $this->db->query("UPDATE {pre}areasample SET state='normal' WHERE id IN ({$ids})");
                insert_log(translate('MENU_AREA_AREA'),translate('OPEN'), array('ids'=> implode(",", $allids)));
                $c = 1;
            } else if ($type == 'reject') {
                $this->db->query("UPDATE {pre}areasample SET state='close' WHERE id IN ({$ids}) AND state!='hide'");
                insert_log(translate('MENU_AREA_AREA'),translate('CLOSE'), array('ids'=> implode(",", $allids)));
                $c = 1;
            } else if ($type == 'new') {
                $this->db->query("UPDATE {pre}areasample SET state='new' WHERE id IN ({$ids})");
                insert_log(translate('MENU_AREA_AREA'),translate('MULTI_OPEN'), array('ids'=> implode(",", $allids)));
                $c = 1;
            } else {
                $r = translate('C_INVALID_PARAMS');
            }
        }
        json_output($c, $r);
    }
}